package com.sh.pangea.dsa.ui.activity;

import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Display;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.nineoldandroids.view.ViewHelper;
import com.sh.lib.dsa.bean.ModuleItem;
import com.sh.lib.dsa.bean.UserInfo;
import com.sh.pangea.dsa.R;
import com.sh.pangea.dsa.Utils.OnCustomDialogListener;
import com.sh.pangea.dsa.Utils.PreferenceUtil;
import com.sh.pangea.dsa.adapter.RecyclerViewAdapter;
import com.sh.pangea.dsa.bean.MenuInfo;
import com.sh.pangea.dsa.ui.fragment.CurrentDataFragment;
import com.sh.pangea.dsa.ui.fragment.MainContentFragment;
import com.sh.pangea.dsa.ui.fragment.MonitoringFragment;
import com.sh.pangea.dsa.ui.fragment.SelectHospitalFragment;
import com.sh.pangea.dsa.view.CircleImageView;
import com.sh.pangea.dsa.view.DialogView;
import com.umeng.socialize.utils.BitmapUtils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import butterknife.BindView;
import butterknife.ButterKnife;

public class MainActivity extends AppCompatActivity implements SelectHospitalFragment.OnListFragmentInteractionListener {
    private static final String TAG = "MainActivity";
    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @BindView(R.id.content_main)
    RelativeLayout contentMain;
    @BindView(R.id.nav_view)
    NavigationView navView;
    @BindView(R.id.drawer_layout)
    DrawerLayout drawerLayout;
    @BindView(R.id.id_recyclerView)
    RecyclerView mRecyclerView;
    @BindView(R.id.hide_button)
    TextView hide_button;

    private CircleImageView headImage;
    private TextView headName;
    private String loginName;

    private Context mContext;
    private Bitmap head;// 头像Bitmap

    private PreferenceUtil mPreferenceUtil;

    //  dialog对话框，确认按钮，0：退出应用，1：注销登录
    private int backType = 0;

    private RecyclerViewAdapter myAdapter;
    private List<String> ids;
    private List<String> names;

    //定时器相关
    private Timer timerDate = null;
    //点击隐藏按钮的次数
    private int time = 0;
    //定时时间
    private int delay = 500;
    //当前选中的条目
    private int position;

    private Handler handler = new Handler() {

        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1:
                    time = 0;
                    break;

                default:
                    break;
            }
        }

        ;
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);
        mContext = this;

        if (mPreferenceUtil == null) {
            mPreferenceUtil = PreferenceUtil.getInstance(this);
        }

        initdate();
        initView();
        initListener();
    }

    private void initdate() {
        names = new ArrayList<>();
        names.add("健康视频");
        names.add("直播");
        names.add("回看");
        names.add("点播");
        names.add("新兴业务");
        names.add("无线认证");
        names.add("医院业务");
        names.add("健康电视APP");
        names.add("权重");
        ids = new ArrayList<>();
        for (int i = 0; i < names.size(); i++) {
            ids.add("T" + i);
        }
        names.add(0, getResources().getString(R.string.current_date));
        ids.add(0, "1");
    }

    private MainContentFragment mMainContentFragment;
    //private MonitoringFragment mMonitoringFragment;
    private CurrentDataFragment mCurrentDataFragment;
    private int LOAD_FIRST = 0;

    private void initView() {
        setSupportActionBar(toolbar);
        getSupportActionBar().setTitle(names.get(LOAD_FIRST));
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                this, drawerLayout, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close) {
        };
        drawerLayout.setDrawerListener(toggle);
        //设置侧拉菜单出现时，主页阴影为透明
        drawerLayout.setScrimColor(Color.TRANSPARENT);
        toggle.syncState();

        mMainContentFragment = new MainContentFragment();
        //mMonitoringFragment = new MonitoringFragment();
        mCurrentDataFragment=new CurrentDataFragment();

//        MenuInfo info = new MenuInfo();
//        info.setId(ids.get(0));
//        info.setName(names.get(0));
//        mMainContentFragment.updateContentList(info);

        getSupportFragmentManager().beginTransaction().replace(R.id.content_main, mCurrentDataFragment).commit();
        headImage = (CircleImageView) navView.getHeaderView(0).findViewById(R.id.imageView);
        headName = (TextView) navView.getHeaderView(0).findViewById(R.id.tv_head_name);

        final UserInfo userInfo = WelcomeActivity.getUserInfo();
        if (userInfo != null) {
            loginName = userInfo.getLoginName();
        }
        Bitmap picToView = getPicToView(loginName);
        if (picToView != null) {
            headImage.setImageBitmap(picToView);
        }
        headName.setText(loginName);

        findViewById(R.id.tv_sign_out).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                String exitStart = mContext.getResources().getString(R.string.exit_app_start);
                String exitEnd = mContext.getResources().getString(R.string.exit_app_end);
                String exitCancel = mContext.getResources().getString(R.string.exit_app_cancel);
                String exitOk = mContext.getResources().getString(R.string.exit_app_ok);
                String exitMsg = exitStart + exitEnd;
                backType = 1;
                showAlertDialog(exitMsg, exitCancel, exitOk, false);

            }
        });

        myAdapter = new RecyclerViewAdapter(names, mContext);
        myAdapter.setSidePosition(LOAD_FIRST);//初次进入默认选中最后一个菜单
        mRecyclerView.setAdapter(myAdapter);

        //设置RecyclerView的布局管理
        LinearLayoutManager manager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
        mRecyclerView.setLayoutManager(manager);

    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
            String exitStart = this.getResources().getString(R.string.exit_app_start);
            String exitEnd = this.getResources().getString(R.string.exit_app_end);
            String appName = this.getResources().getString(R.string.app_name);
            String exitCancel = this.getResources().getString(R.string.exit_app_cancel);
            String exitOk = this.getResources().getString(R.string.exit_app_ok);
            String exitMsg = exitStart + appName + exitEnd;
            backType = 0;
            showAlertDialog(exitMsg, exitCancel, exitOk, false);
            return true;
        }

        return super.onKeyDown(keyCode, event);
    }

    protected void showAlertDialog(String msg, String cancel, String confim,
                                   final boolean isSingleButton) {
        AlertDialog alertDialog = new AlertDialog.Builder(mContext).create();
        alertDialog.show();
        alertDialog.setCancelable(false);
        alertDialog.setCanceledOnTouchOutside(false);
        Window window = alertDialog.getWindow();
        WindowManager m = getWindowManager();
        Display d = m.getDefaultDisplay();
        WindowManager.LayoutParams params = window.getAttributes();
        params.width = (int) (d.getHeight() * 0.48);
        params.height = (int) (d.getWidth() * 0.45);
        window.setAttributes(params);
        DialogView dialogView = new DialogView(mContext);
        dialogView.creatDialog(msg, cancel, confim, isSingleButton, new OnCustomDialogListener() {
            @Override
            public void cancel() {

            }

            @Override
            public void confirm() {
                if (backType == 1) {
                    mPreferenceUtil.saveString("userName", "");
                    mPreferenceUtil.saveString("passWord", "");
                    Intent intent = new Intent(MainActivity.this, WelcomeActivity.class);
                    startActivity(intent);
                    finish();
                } else if (backType == 0) {
                    finish();
                }
            }
        });
        dialogView.setDialog(alertDialog);
        window.setContentView(dialogView);
        alertDialog.show();
    }

    private void initListener() {
        drawerLayout.addDrawerListener(new DrawerLayout.DrawerListener() {
            @Override
            public void onDrawerSlide(View drawerView, float slideOffset) {
                View mContent = drawerLayout.getChildAt(0);
                View mMenu = drawerView;
                float scale = 1 - slideOffset;
                ViewHelper.setAlpha(mMenu, 0.6f + 0.4f * (1 - scale));
                ViewHelper.setTranslationX(mContent,
                        mMenu.getMeasuredWidth() * (1 - scale));
                ViewHelper.setPivotX(mContent, 0);
                ViewHelper.setPivotY(mContent,
                        mContent.getMeasuredHeight() / 2);
                mContent.invalidate();
            }

            @Override
            public void onDrawerOpened(View drawerView) {

            }

            @Override
            public void onDrawerClosed(View drawerView) {

            }

            @Override
            public void onDrawerStateChanged(int newState) {

            }
        });
        headImage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //TODO 点击图片调出照相机功能
                showPopupWindow(headImage);
            }
        });
        myAdapter.setOnItemClickListener(new RecyclerViewAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                if (position != 9){
                    MainActivity.this.position = position;
                }
                if ("T8".equals(ids.get(position))){
                    // 显示权重界面
                    Intent intent = new Intent(MainActivity.this,AnticipativeDataActivity.class);
                    startActivityForResult(intent,6);
                }else{
                    getSupportActionBar().setTitle(names.get(position));
                    MenuInfo info = new MenuInfo();
                    info.setId(ids.get(position));
                    info.setName(names.get(position));
                    if (position == LOAD_FIRST) {
                        // 最后一个，显示实时数据
                        getSupportFragmentManager().beginTransaction().replace(R.id.content_main, mCurrentDataFragment).commit();
                    } else {
                        // 显示分类
                        showMainContent(info);
                    }
                    myAdapter.setSidePosition(position);//用于把选中的条目背景颜色变色
                    myAdapter.notifyDataSetChanged();
                    drawerLayout.closeDrawer(GravityCompat.START);
                }
            }

            @Override
            public void onItemLongClick(View view, int position) {

            }
        });

        hide_button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Log.i("delay","1");
                stopTimer();
                time++;
                startTimers();
                if (time == 5){
                    myAdapter.setShowAnticipativeDate(false);
                    myAdapter.notifyDataSetChanged();
                }
            }
        });
    }

    /**
     * 启动定时器
     */
    private void startTimers() {
        timerDate = new Timer();
        // 更新时间
        timerDate.schedule(new TimerTask() {

            @Override
            public void run() {
                handler.sendEmptyMessage(1);
            }
        }, delay);
    }

    /**
     * 关闭定时器
     **/
    public void stopTimer() {
        if (timerDate != null) {
            timerDate.cancel();
        }
    }

    private void showMainContent(MenuInfo info) {
        if (mMainContentFragment == null) {
            mMainContentFragment = new MainContentFragment();
        }
        mMainContentFragment.updateContentList(info);
        getSupportFragmentManager().beginTransaction().replace(R.id.content_main, mMainContentFragment).commit();
    }

    /**
     * 显示相册选取
     */
    private void showPopupWindow(View imageView) {
        // 一个自定义的布局，作为显示的内容
        View contentView = LayoutInflater.from(mContext).inflate(
                R.layout.pop_window, null);
        final PopupWindow popupWindow = new PopupWindow(contentView,
                300, 200, true);
        // 设置按钮的点击事件
        RelativeLayout button_pai = (RelativeLayout) contentView
                .findViewById(R.id.pop_rl_photograph);
        button_pai.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {

                Intent intent2 = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                intent2.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(Environment.getExternalStorageDirectory(), "head.jpg")));
                startActivityForResult(intent2, 2);// 采用ForResult打开
                popupWindow.dismiss();

            }
        });
        RelativeLayout button_xiang = (RelativeLayout) contentView
                .findViewById(R.id.pop_rl_photo_album);
        button_xiang.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View arg0) {
                Intent intent1 = new Intent(Intent.ACTION_PICK, null);
                intent1.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
                startActivityForResult(intent1, 1);
                popupWindow.dismiss();

            }
        });

        popupWindow.setTouchable(true);

        popupWindow.setTouchInterceptor(new View.OnTouchListener() {

            @Override
            public boolean onTouch(View v, MotionEvent event) {

                Log.i("mengdd", "onTouch : ");

                return false;
            }
        });

        popupWindow.setBackgroundDrawable(getResources().getDrawable(R.color.transparent));
        popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {

            @Override
            public void onDismiss() {
            }
        });
        popupWindow.showAsDropDown(imageView, 200, -180);
//        popupWindow.showAtLocation(imageView, Gravity.RIGHT, 0, 0);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        switch (requestCode) {

            case 1:
                if (resultCode == RESULT_OK) {
                    cropPhoto(data.getData());
                }

                break;
            case 2:
                if (resultCode == RESULT_OK) {
                    File temp = new File(Environment.getExternalStorageDirectory()
                            + "/head.jpg");
                    cropPhoto(Uri.fromFile(temp));
                }

                break;

            case 3:
                if (data != null) {
                    Bundle extras = data.getExtras();
                    head = extras.getParcelable("data");
                    if (head != null) {
                        /**
                         * 上传服务器代码
                         */
                        setPicToView(head, loginName);// 保存在SD卡中
                        headImage.setImageBitmap(head);// 用ImageView显示出来
                    }
                }
                break;
            case 6:
                if (data!=null){
                    Log.i("实时数据aaa","实时数据aaa ： " + position);
                    if ("1".equals(ids.get(position))){
                        Log.i("实时数据","实时数据");
                        mCurrentDataFragment.refreshData();
                    }
                    boolean isHide = data.getBooleanExtra("ishide",true);
                    if (isHide){
                        myAdapter.setShowAnticipativeDate(isHide);
                        myAdapter.notifyDataSetChanged();
                    }
                }
                break;
        }
    }

    private void setPicToView(Bitmap mBitmap, String name) {
        String sdStatus = Environment.getExternalStorageState();
        if (!sdStatus.equals(Environment.MEDIA_MOUNTED)) { // 检测sd是否可用
            return;
        }
        FileOutputStream b = null;
        String fileName = Environment.getExternalStorageDirectory().getPath() + "/" + name + "_head.png";// 图片名字
        Log.i("MySelfAccounttActivity", "图片路径==>" + fileName);
        File file = new File(fileName);
        if (file.exists()) {
            file.delete();
        }
        try {
            b = new FileOutputStream(fileName);
            mBitmap.compress(Bitmap.CompressFormat.PNG, 100, b);// 把数据写入文件
            b.close();
        } catch (IOException e) {
            Log.e(TAG, e.getLocalizedMessage());
        } finally {
            try {
                if (b != null) {
                    // 关闭流
                    b.close();
                }
            } catch (IOException e) {
                Log.e(TAG, e.getLocalizedMessage());
            }

        }
    }

    private Bitmap getPicToView(String name) {
        Bitmap bitmap = null;
        String externalStorageState = Environment.getExternalStorageState();
        if (externalStorageState.equals(Environment.MEDIA_MOUNTED)) {
            String fileName = Environment.getExternalStorageDirectory().getPath() + "/" + name + "_head.png";
            File file = new File(fileName);
            if (file.exists()) {
                bitmap = BitmapUtils.getBitmapFromFile(fileName);
            }
        }

        return bitmap;
    }


    /**
     * 调用系统的裁剪
     *
     * @param uri
     */
    public void cropPhoto(Uri uri) {
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");
        intent.putExtra("crop", "true");
        // aspectX aspectY 是宽高的比例
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        // outputX outputY 是裁剪图片宽高
        intent.putExtra("outputX", 150);
        intent.putExtra("outputY", 150);
        intent.putExtra("return-data", true);
        startActivityForResult(intent, 3);
    }

    @Override
    public void onBackPressed() {
        DrawerLayout drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
        if (drawerLayout.isDrawerOpen(GravityCompat.START)) {
            drawerLayout.closeDrawer(GravityCompat.START);
        } else {
            super.onBackPressed();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    public void onListFragmentInteraction(ModuleItem item) {
        Toast.makeText(this, "点击了" + item.getName(), Toast.LENGTH_SHORT).show();
    }
}
